/**
 * The DeleteAction, when performed, deletes all selected Shapes.
 * 
 * @author Giuseppe Mendola (giuseppe.mendola@usi.ch);Gregory Banfi (gregory.banfi@usi.ch);
 */

package ch.usi.inf.pf2.gui;

import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;

import ch.usi.inf.pf2.Component;

import java.util.ArrayList;

@SuppressWarnings("serial")
public final class DeleteAction extends AbstractAction {

	private final Model model;

	public DeleteAction(final Model model) {
		this.model = model;
		putValue(NAME, "Delete");
		final ImageIcon icon = new ImageIcon(getClass()
				.getResource("cross.png"));
		putValue(SMALL_ICON, icon);
		putValue(SHORT_DESCRIPTION, "Delete the selected components");

		setEnabled(Model.getSelection().getSize() > 0);

		// register listeners
		Model.getSelection().addSelectionListener(new SelectionListener() {
			@Override
			public void selectionChanged() {
				final int count = Model.getSelection().getSize();
				putValue(
						SHORT_DESCRIPTION,
						count == 0 ? "Delete the selected components"
								: ("Delete the " + count + " selected components"));
				setEnabled(count > 0);
			}
		});
	}

	/**
	 * This method creates a new ArrayList<Component>, which contains all the
	 * selected component, then those element are remove from the drawing and
	 * selection objects.
	 */
	@Override
	public void actionPerformed(final ActionEvent ev) {
		// save selected shapes
		final ArrayList<Component> originallySelectedComponents = new ArrayList<Component>();
		for (final Component component : Model.getSelection()) {
			originallySelectedComponents.add(component);
		}
		// remove selected shapes
		for (final Component component : originallySelectedComponents) {
			Model.getSelection().remove(component);
			Model.getDrawing().remove(component);
			Model.getDrawing();
			Drawing.getGates().remove(component);
			Model.getDrawing().getMultipleInputs().clear();
		}
	}
}
